package com.njtoyo.taxi.admin.service.business.driver.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.mapper.master.entity.Company;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverExtraInformation;
import com.njtoyo.taxi.admin.mapper.master.entity.GeoCanton;
import com.njtoyo.taxi.admin.mapper.master.entity.Taxi;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.rest.export.driver.DriverServiceLogExportData;
import com.njtoyo.taxi.admin.rest.presenter.business.driver.DriverServiceLogPresenter;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.AdminUserIdentityPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.driver.DriverServiceLogExportWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.driver.DriverServiceLogQueryWrapper;
import com.njtoyo.taxi.admin.service.business.driver.DriverServiceLogsService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static java.util.stream.Collectors.toList;

@Service
public class DriverServiceLogsServiceImpl implements DriverServiceLogsService {
    @Autowired
    private DriverServiceLogMapper driverServiceLogMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private GeoCantonMapper geoCantonMapper;
    @Autowired
    private TaxiMapper taxiMapper;
    @Autowired
    private DriverExtraInformationMapper driverExtraInformationMapper;

    /**
     * 出车司机名单
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<DriverServiceLogPresenter>> dailyWorkingDriver(AdminUser adminUser, DriverServiceLogQueryWrapper wrapper) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        switch (adminUser.getAccountType()) {
            case company:
                wrapper.setCompanyIds(identity.getCompanyIds());
                break;
            case canton:
                wrapper.setCantonIds(identity.getCantonIds());
        }
        Page<DriverServiceLogPresenter> page = driverServiceLogMapper.dailyWorkingDriver(wrapper);
        List<Long> ids = page.getRecords().stream()
                .map(DriverServiceLogPresenter::getId)
                .collect(toList());

        List<Long> cantonIds = page.getRecords().stream()
                .map(DriverServiceLogPresenter::getCantonId)
                .collect(toList());
        List<Long> taxiIds = page.getRecords().stream()
                .map(DriverServiceLogPresenter::getTaxiId)
                .collect(toList());
        //验证是否存在数据
        if (ids.size() == 0) {
            return RestResult.success(page);
        }
        //车辆
        QueryWrapper<Taxi> taxiQueryWrapper = new QueryWrapper<>();
        taxiQueryWrapper.select("id", "plate_number", "company_id");
        taxiQueryWrapper.in("id", taxiIds);
        List<Taxi> taxis = taxiMapper.selectList(taxiQueryWrapper);
        List<Long> companyIds = taxis.stream()
                .map(Taxi::getCompanyId)
                .collect(toList());
        //公司
        QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
        companyQueryWrapper.select("id", "name");
        companyQueryWrapper.in("id", companyIds);
        List<Map<String, Object>> companyList = companyMapper.selectMaps(companyQueryWrapper);
        //行政区ID
        QueryWrapper<GeoCanton> geoCantonQueryWrapper = new QueryWrapper<>();
        geoCantonQueryWrapper.select("id", "name");
        geoCantonQueryWrapper.in("id", cantonIds);
        List<Map<String, Object>> geoCantons = geoCantonMapper.selectMaps(geoCantonQueryWrapper);
        // diver
        QueryWrapper<DriverExtraInformation> driverExtraInformationQueryWrapper = new QueryWrapper<>();
        driverExtraInformationQueryWrapper.select("driver_id", "vehicle_licence_number", "qualification_certificate_number");
        driverExtraInformationQueryWrapper.in("driver_id", ids);
        List<Map<String, Object>> driverExtraInfos = driverExtraInformationMapper.selectMaps(driverExtraInformationQueryWrapper);

        for (DriverServiceLogPresenter p : page.getRecords()) {
            Long cantonId = p.getCantonId();
            Long taxiId = p.getTaxiId();
            Long driverId = p.getId();
            for (Taxi t : taxis) {
                if (taxiId.equals(t.getId())) {
                    p.setPlateNumber(t.getPlateNumber());
                    p.setCompanyId(t.getCompanyId());
                }
            }
            for (Map c : companyList) {
                if (c.get("id").equals(p.getCompanyId())) {
                    p.setCompanyName(String.valueOf(c.get("name")));
                }
            }
            for (Map g : geoCantons) {
                if (cantonId.equals(g.get("id"))) {
                    p.setCantonName(String.valueOf(g.get("name")));
                }
            }
            for (Map<String, Object> e : driverExtraInfos) {
                if (driverId.equals(e.get("driverId"))) {
                    Object vehicleLicenceNumber = e.get("vehicleLicenceNumber");
                    if (Objects.nonNull(vehicleLicenceNumber)) {
                        p.setVehicleLicenceNumber(vehicleLicenceNumber.toString());
                    }
                    Object qualificationCertificateNumber = e.get("qualificationCertificateNumber");
                    if (Objects.nonNull(qualificationCertificateNumber)) {
                        p.setQualificationCertificateNumber(qualificationCertificateNumber.toString());
                    }
                }
            }
        }
        return RestResult.success(page);
    }

    /**
     * 出车司机名单导出Excel列表
     *
     * @param wrapper
     * @return
     */
    @Override
    public void export(AdminUser adminUser,DriverServiceLogExportWrapper wrapper, HttpServletResponse response) throws IOException {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        switch (adminUser.getAccountType()) {
            case company:
                wrapper.setCompanyIds(identity.getCompanyIds());
                break;
            case canton:
                wrapper.setCantonIds(identity.getCantonIds());
        }
        List<DriverServiceLogPresenter> list = driverServiceLogMapper.dailyWorkingDriverExport(wrapper);
        List<Long> ids = list.stream()
                .map(DriverServiceLogPresenter::getId)
                .collect(toList());
        List<Long> cantonIds = list.stream()
                .map(DriverServiceLogPresenter::getCantonId)
                .collect(toList());
        List<Long> taxiIds = list.stream()
                .map(DriverServiceLogPresenter::getTaxiId)
                .collect(toList());
        //验证是否存在数据
        if (ids.size() != 0) {
            //车辆
            QueryWrapper<Taxi> taxiQueryWrapper = new QueryWrapper<>();
            taxiQueryWrapper.select("id", "plate_number", "company_id");
            taxiQueryWrapper.in("id", taxiIds);
            List<Taxi> taxis = taxiMapper.selectList(taxiQueryWrapper);
            List<Long> companyIds = taxis.stream()
                    .map(Taxi::getCompanyId)
                    .collect(toList());
            //公司
            QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
            companyQueryWrapper.select("id", "name");
            companyQueryWrapper.in("id", companyIds);
            List<Map<String, Object>> companyList = companyMapper.selectMaps(companyQueryWrapper);
            //行政区ID
            QueryWrapper<GeoCanton> geoCantonQueryWrapper = new QueryWrapper<>();
            geoCantonQueryWrapper.select("id", "name");
            geoCantonQueryWrapper.in("id", cantonIds);
            List<Map<String, Object>> geoCantons = geoCantonMapper.selectMaps(geoCantonQueryWrapper);

            for (DriverServiceLogPresenter p : list) {
                Long cantonId = p.getCantonId();
                Long taxiId = p.getTaxiId();
                for (Taxi t : taxis) {
                    if (taxiId.equals(t.getId())) {
                        p.setPlateNumber(t.getPlateNumber());
                        p.setCompanyId(t.getCompanyId());
                    }
                }
                for (Map c : companyList) {
                    if (c.get("id").equals(p.getCompanyId())) {
                        p.setCompanyName(String.valueOf(c.get("name")));
                    }
                }
                for (Map g : geoCantons) {
                    if (cantonId.equals(g.get("id"))) {
                        p.setCantonName(String.valueOf(g.get("name")));
                    }
                }
            }
        }
        String fileName = URLEncoder.encode("司机出车信息", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DriverServiceLogExportData.class)
                .sheet(0)
                .doWrite(list);
    }
}
